<template>
	<view class="page">
		<!-- 页面头部内容开始 -->
		<vk-data-page-header
			:title="page.title"
			:show-back="true"
			@back="pageBack()"
		></vk-data-page-header>
		<!-- 页面头部内容结束 -->
		<view class="page-body">
			<!-- 页面主体内容开始  max-height="inherit"-->
			<vk-data-form
				ref="form1"
				v-model="form1"
				:rules="formData1.rules"
				:action="formData1.action"
				:form-type="formData1.formType"
				:columns='formData1.columns'
				label-width="100px"
				:footer-show="false"
				:loading.sync="formData1.loading"
				:before-action="formData1.beforeAction"
				@success="formSuccess"
			>


				<template v-slot:exp_time_mode="{ form, keyName }">
					<view style="">
						<view>
							<el-form-item prop="exp_time_mode" :inline-message="true">
								<el-radio v-model="form[keyName]" :label="0">
									<text>长期有效</text>
									<text style="margin-left: 20px;color: #909399;font-size: 12px;">更改有效期仅对新付款订单有效</text>
								</el-radio>
							</el-form-item>
						</view>
						<view style="margin-top: 10px;">
							<el-form-item prop="exp_time_range" :inline-message="true">
								<el-radio v-model="form[keyName]" :label="1">
									<text>固定时间</text>
									<vk-data-input-date-time v-model="form.exp_time_range" type="datetimerange" size="small" style="margin-left: 20px;" />
								</el-radio>
							</el-form-item>
						</view>
						<view style="margin-top: 10px;">
							<el-form-item prop="exp_time_rule" :inline-message="true">
								<el-radio v-model="form[keyName]" :label="2">
									<text>购买后</text>
									<vk-data-input-number v-model="form.exp_time_rule[0]" :precision="0" width="120px" size="small" placeholder="多少" style="margin-left: 32px;" />
									<text style="margin-left: 5px;">天后生效，有效期</text>
									<vk-data-input-number v-model="form.exp_time_rule[1]" :precision="0" width="120px" size="small" placeholder="多少" style="margin-left: 5px;" />
									<text style="margin-left: 5px;">天</text>
								</el-radio>
							</el-form-item>
						</view>
					</view>
				</template>

				<!-- <template v-slot:goods_sku="{ form, keyName, val }">
					<vk-data-input-goods-sku
						v-model="form1"
						:props="{ spec_list:'spec_list', sku_list:'sku_list' }"
						:textdata="{ specTitle: '多规格', '价格':'销售价' }"
					></vk-data-input-goods-sku>
				</template> -->

			</vk-data-form>
			<!-- 页面主体内容结束 -->
		</view>
		<view class="page-footer">
			<!-- 页面底部内容开始 -->
			<el-button plain class="footer-back-btn" @click="pageBack()">返回</el-button>
			<el-button :loading="formData1.loading" type="primary" class="footer-update-btn" @click="submitForm" style="margin-left: 50px;">{{ page.submitText }}</el-button>
			<!-- 页面底部内容开始 -->
		</view>
	</view>
</template>

<script>
	var that;													// 当前页面对象
	var vk = uni.vk;									// vk实例
	var originalForms = {};						// 表单初始化数据
	export default {
		data() {
			// 页面数据变量
			return {
				// 页面配置数据
				page:{
					title:"",
					submitText:"",
					pickerOptions:vk.pubfn.elementUtil.datePickerRangeOptions(),
					backPage:"/pages/goods/list"
				},
				// 表单请求数据
				form1:{
					type:0,
					is_free_delivery:true,
					exp_time_mode:0,
					goods_detail_mode:0,
					exp_time_rule:[],
					exp_time_range:[],
					spec_list:[],
					sku_list:[],
					is_on_sale:true,	// 默认上架
					initial_sell_count:0,
					is_real:true,
					is_new:true,
					belong_integral: false,
					sort:0,
					cart_rule:{
						step:1,                 //步进值
						min:1,			            //最少起购量
						max:100000,					    //单次最大购买数量(0为不限制)
						step_strictly:false     //是否只能输入对应的倍数
					},
					limit_buy_rule:{
						activity_limit_num:0,        //活动期间内总限购 0代表不限购
						every_day_limit_num:0,			 //常规每日限购 0代表不限购
						limit_time:[]
					},
					integral_rule:{
						is_calc:false,
						is_fixed_calc:false,
						proportion_value:"",
						fixed_value:"",
						is_level_k:true
					}
				},
				formData1:{
					// 表单请求地址
					action:"admin/business/sys/goods.addUpdate",
					// 表单字段显示规则
					columns:[
						// 商品类型
						{ key:"", title:"商品类型", type:"bar-title" },
						{
						  key:"type", title:"", type:"radio", showLabel:false,
						  itemWidth:80,
							optionType:"button",
						  data:[
						    { value:0, label:"实物商品（需物流）" },
						    { value:1, label:"电子卡券（无需物流）" }
						  ],
							disabled:["update"]
						},
						// 基本信息
						{ key:"", title:"基本信息", type:"bar-title" },
						{ key:"name", title:"商品名", type:"text", width:600, maxlength:20, showWordLimit:true,
							tips:"一个好的商品名称会增加商品的销量！20字以内"
						},
						{
							key:"category_ids", title:"选择分类", type:"cascader", width:600,
							action:"admin/business/sys/goodsCategory.kh_getList",
							props:{
								list:"rows",
								value:"_id",
								label:"name",
								children:"children",
								checkStrictly:true,
								emitPath:false,
								multiple:true
							},
							tips:"准确选择商品分类有助于完善商品信息与数据分析。"
						},
						{ key:"goods_desc", title:"详细描述", type:"text", width:600, maxlength:60, showWordLimit:true,
							tips:"在商品详情页标题下面展示卖点信息，60字以内"
						},
						{ key:"keywords", title:"商品关键字", type:"text", width:600, maxlength:60, showWordLimit:true },
						// 商品配送方式
						{ key:"", title:"商品配送方式", type:"bar-title", showRule:"type==0" },
						{
							key:"is_free_delivery", title:"运费", type:"radio",
							itemWidth:80,
							data:[
								{ value:true, label:"包邮" },
								{ value:false, label:"不包邮" }
							],
							showRule:"type==0"
						},
						{
							key:"freight_id", title:"运费模板", type:"remote-select", placeholder:"请选择运费模板", width:400,
							action:"admin/business/sys/freight.getList",
							props:{ list:"rows", value:"_id", label:"name" },
							showAll:true,
							showRule:"type==0&&is_free_delivery==false"
						},
						// 电子卡券专属字段
						{ key:"", title:"有效期", type:"bar-title", showRule:"type==1" },
						{ key:"exp_time_mode", title:"", type:"text", showRule:"type==1" },
						// 图片信息
						{ key:"", title:"图片信息", type:"bar-title" },
						//{ key:"goods_thumb", title:"商品缩略图", type:"image", limit:1, tips:"建议尺寸：800*800像素，限1张" },
						{ key:"goods_thumb", title:"商品缩略图", type:"file-select", placeholder:"请选择图片", fileType:"image", tips:"建议尺寸：800*800像素，限1张" },

						//{ key:"goods_banner_imgs", title:"商品轮播图", type:"image", limit:9, tips:"建议尺寸：800*800像素，最多上传9张"},
						{ key:"goods_banner_imgs", title:"商品轮播图", type:"file-select", placeholder:"请选择图片", fileType:"image", multiple:true, multipleLimit:9, tips:"建议尺寸：800*800像素，最多上传9张" },

						// 商品详情介绍
						{ key:"", title:"商品详情介绍", type:"bar-title", showRule:"type==0" },
						{
							key:"goods_detail_mode", title:"展示方式", type:"radio",
							itemWidth:80,
							data:[
								{ value:0, label:"简易模式（纯图片）" },
								{ value:1, label:"富文本模式（图片+文字）" }
							],
						},

						// { key:"goods_detail_imgs", title:"商品详情图", type:"image",
						// 	limit:20,
						// 	tips:"建议尺寸：800*800像素，最多上传20张",
						// 	showRule:"goods_detail_mode==0"
						// },
						{ key:"goods_detail_imgs", title:"商品详情图", type:"file-select", placeholder:"请选择图片", fileType:"image",
							multiple:true,
							multipleLimit:20,
							tips:"建议尺寸：800*任意，最多上传20张",
							showRule:"goods_detail_mode==0"
						},

						{ key:"goods_detail_body", title:"商品详情图文", type:"editor", width:"750px", showRule:"goods_detail_mode==1" },
						{ key:"goods_tags", title:"商品标签", type:"tag" },
						{ key:"goods_services", title:"商品服务", type:"tag" },
						// 多规格
						{ key:"goods_sku", title:"", type:"goods-sku", showLabel:false, props: { spec_list:"spec_list", sku_list:"sku_list" } },
						// 商品配置
						{ key:"", title:"商品配置", type:"bar-title" },
						{ key:"is_on_sale", title:"是否上架", type:"switch" },
						{ key:"is_new", title:"是否新品", type:"switch" },
						{ key:"is_best", title:"是否精品", type:"switch" },
						{ key:"is_hot", title:"是否热销", type:"switch" },
						{ key:"belong_integral", title:"是否属于积分商场", type:"switch" },
						{ key:"disable_vip", title:"禁用会员价", type:"switch",
							tips:"禁用后，该商品不能使用会员价进行优惠！"
						},
						{ key:"disable_coupon", title:"禁用优惠券", type:"switch",
							tips:"禁用后，该商品不能使用优惠券进行优惠！"
						},

						{ key:"", title:"购物车规则", type:"bar-title" },
						{ key:"cart_rule", title:"", type:"object", width:600, showLabel: false,
							columns:[
								{ key:"step", title:"购物车步长", type:"number", controls:true, width:180, tips:"每按一次+后，增加的数量X" },
								{ key:"min", title:"最少起购量", type:"number", controls:true, width:180, tips:"用户购买时，每单最低需购买的数量" },
								{ key:"max", title:"每单最多购", type:"number", controls:true, width:180, tips:"用户购买时，每单最多可购买的数量" },
								{ key:"step_strictly", title:"必须是步长的倍数", type:"switch", labelWidth:140, tips:"如需要用户下单必须是X的倍数（如必须是3的倍数，3，6，9，...），则开启此项" },
							]
						},

						{ key:"", title:"商品限购规则", type:"bar-title" },
						{ key:"limit_buy_rule", title:"", type:"object", width:600, showLabel: false,
							columns:[
								{ key:"every_day_limit_num", title:"常规每日限购", type:"number", controls:true, width:180, tips:"0代表不限购" },
								{ key:"activity_limit_num", title:"活动内总限购", type:"number", controls:true, width:180, tips:"0代表不限购" },
								{ key:"limit_time", title:"限购时间区间", type:"date", dateType:"datetimerange", width:400, tips:"表示用于计算总限购活动的时间区间，注意：若当前时间不在此区间则用户无法购买。若不设置，则视为时间区间为永久生效" },
							]
						},
						{ key:"", title:"积分规则", type:"bar-title" },
						{ key:"integral_rule", title:"", type:"object", width:180, showLabel: false,
							columns:[
								{ key:"is_calc", title:"是否赠送积分", type:"switch", activeValue:true, inactiveValue:false, tips:"积分在付款后就会获得，若商品发生退款，积分会扣除，若积分不够扣除，则用户无法申请退款（商家主动退款依然可以，此时积分会清0）", },
								{
								  key:"is_fixed_calc", title:"积分计算方式", type:"radio",
								  itemWidth:80,
								  data:[
								    { value:false, label:"百分比" },
								    { value:true, label:"固定值" }
								  ],
									showRule:(res)=>{
										return vk.pubfn.getData(res,"integral_rule.is_calc",false);
									},
								},
								{ key:"proportion_value", title:"百分比", type:"percentage", width:180, tips:"购买后按付款金额*百分比计算积分",
									showRule:(res)=>{
										return vk.pubfn.getData(res,"integral_rule.is_calc",false) && vk.pubfn.getData(res,"integral_rule.is_fixed_calc") == false;
									},
								},
								{ key:"fixed_value", title:"固定值", type:"number", width:180, tips:"购买后赠送多少积分",
									showRule:(res)=>{
										return vk.pubfn.getData(res,"integral_rule.is_calc",false) && vk.pubfn.getData(res,"integral_rule.is_fixed_calc") == true;
									},
								},
								{ key:"is_level_k", title:"受VIP影响", type:"switch", activeValue:true, inactiveValue:false, tips:"开启后，会乘以VIP等级中的积分倍率",
									showRule:(res)=>{
										return vk.pubfn.getData(res,"integral_rule.is_calc",false);
									},
								},
							]
						},
						{ key:"", title:"其他信息", type:"bar-title" },
						{ key:"initial_sell_count", title:"初始销量", type:"number", width:150 },
						{ key:"seller_note", title:"商家备注", type:"textarea", width:600,
							autosize:{ minRows:4, maxRows:10 },
							maxlength:200,
							showWordLimit:true,
							tips:"此备注仅商家可见"
						},
						{ key:"sort", title:"排序值", type:"number", width:600, tips:"值越大，商品显示越在前面。" },
						// goods_detail_body 富文本字段
					],
					// 表单验证规则
					rules:{
						name:[
							{ required:true, message:'商品名称为必填字段', trigger:'blur' },
							{ min:2,max:20, message:'商品名长度为2-20个字符', trigger:'blur' }
						],
						sku_list:[
							{ required:true, message:'商品规格为必填字段', trigger:'blur' },
						],
						is_on_sale:[
							{ required:true, message:'是否上架为必填字段', trigger:['blur','change'] },
						],
						goods_thumb:[
							{ required:true, message:'请上传商品缩略图', trigger:['blur','change'] },
						],
						goods_banner_imgs:[
							{ required:true, message:'请上传商品banner图', trigger:['blur','change'] },
						],
						freight_id:[
							{ required:true, message:'请选择运费模板', trigger:'blur' },
						],
						exp_time_range:[
							{ validator: (rule, value, callback)=>{
								let { form1 } = this;
								if (form1.type === 1 && form1.exp_time_mode === 1 && vk.pubfn.isNull(value)) {
									callback(new Error('请选择时间范围'));
								} else {
									callback();
								}
							}, trigger:['blur','change'] }
						],
						exp_time_rule:[
							{ validator: (rule, value, callback)=>{
								let { form1 } = this;
								if (form1.type === 1 && form1.exp_time_mode === 2 && vk.pubfn.isNull(value)) {
									callback(new Error('请输入有效期'));
								} else {
									callback();
								}
							}, trigger:['blur','change'] }
						],
					},
					// add 代表添加 update 代表修改
					formType:'',
					// 是否显示表单1 的弹窗
					show:false,
					// 表单是否请求中
					loading:false,
					// 请求前逻辑
					beforeAction:function(){
						// 不勾选的不进行提交
						let saveinfo = [...that.form1.sku_list];
						for(let i=0;i<saveinfo.length;i++){
							let item = saveinfo[i];
							if(item.disabled || vk.pubfn.isNullAll(item.price,item.stock,item.weight)){
								saveinfo.splice(i,1);
								i--;
							}
						}
						return {
							sku_list:saveinfo
						};
					},
				}
			}
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady(){

		},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {


		},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {


		},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options){
				originalForms["form1"] = vk.pubfn.copyObject(that.form1);
				that.formData1.formType = options.mode;
				that.form1.mode = options.mode;
				if(options.mode === "update"){
					that.page.title = "商品编辑";
					that.page.submitText = "修改";
					vk.callFunction({
						url: 'admin/business/sys/goods.pub_findGoodsInfo',
						title:'请求中...',
						data:{
							_id:options._id
						},
						success:function(data) {
							let form1 = vk.pubfn.copyObject(that.form1);
							if(vk.pubfn.isNotNull(data.info.goods_detail_body)){
								data.info.goods_detail_body = vk.myfn.imgVideoTagTurn(data.info.goods_detail_body, 1);
								
							}
							
							that.form1 = vk.pubfn.objectAssign(form1, data.info);
						}
					});
				}
				else{
					that.page.title = "商品添加";
					that.page.submitText = "添加";
					that.form1.spec_list = [
						{
							name:'默认',
							list:[
								{	name:'默认' }
							]
						}
					];

					if(options._id){
						vk.callFunction({
							url: 'admin/business/sys/goods.pub_findGoodsInfo',
							title:'请求中...',
							data:{
								_id:options._id
							},
							success:function(data) {
								let form1 = vk.pubfn.copyObject(that.form1);
								let goodsInfo = data.info;
								delete goodsInfo._id;
								delete goodsInfo._add_time;
								delete goodsInfo._add_time_str;
								delete goodsInfo.on_sale_time;
								delete goodsInfo.update_time;
								delete goodsInfo.delete_time;
								delete goodsInfo.seller_note;
								goodsInfo.initial_sell_count = 0;
								goodsInfo.total_sell_count = 0;
								goodsInfo.real_sell_count = 0;
								goodsInfo.comment_count = 0;
								goodsInfo.view_count = 0;
								goodsInfo.name = goodsInfo.name+"-copy";
								if(vk.pubfn.isNotNull(data.info.goods_detail_body)){
									goodsInfo.goods_detail_body = vk.myfn.imgVideoTagTurn(goodsInfo.goods_detail_body, 1);
								}								
								that.form1 = vk.pubfn.objectAssign(form1, goodsInfo);
								that.getSortMax();
							}
						});
					} else {
						that.getSortMax();
					}
				}
			},
			getSortMax(){
				vk.callFunction({
					url: 'admin/business/sys/goods.getMaxSort',
					data: {},
					success: (data) => {
						that.form1.sort = data.sort + 1;
					}
				});
			},
			// 页面跳转
			pageTo(path){
				vk.navigateTo(path);
			},
			// 页面返回
			pageBack(res={}){
				if (res.formType == "update") {
					const eventChannel = this.getOpenerEventChannel();
					if (eventChannel.emit) eventChannel.emit('update', res.data.info);
				} else if (res.formType == "add") {
					const eventChannel = this.getOpenerEventChannel();
					if (eventChannel.emit) eventChannel.emit('add');
				}
				const pages = getCurrentPages();
				if (pages.length>1 && pages[0].route !== that.$page.route) {
					vk.navigateBack();
				} else if(that.page.backPage) {
					vk.navigateTo(that.page.backPage);
				}
				setTimeout(()=>{
					vk.menuTabs.closeTabs("/pages/goods/edit");
				},600);
			},

			// 表单重置
			resetForm(){
				vk.pubfn.resetForm(originalForms, that);
			},
			// 表单提交
			submitForm(){
				that.form1.mode = that.options.mode;
				if(that.options.mode=='copy'){
					that.form1.mode='add'
				}
				that.$refs.form1.submitForm();
			},
			formSuccess(res){
				if(that.formData1.formType == "add"){
					that.$alert('商品添加成功', '提示', {
						confirmButtonText: '好的',
						callback: action => {
							that.pageBack(res);
						}
					});
				}else{
					that.$alert('商品修改成功', '提示', {
						confirmButtonText: '好的',
						callback: action => {
							that.pageBack(res);
						}
					});
				}
			},
		},
		watch: {

		},
		// 计算属性
		computed:{

		}
	}
</script>
<style lang="scss" scoped>
	.padding-10{
		padding: 10px;
	}
	.marginLeft-10{
		margin-left: 10px;
	}
	.footer-update-btn{
		width: 80px;
	}

	.footer-back-btn{
		margin-left: 20px;
		width: 80px;
	}

	/* 上传组件开始 */
	::v-deep .sku-image .vk-data-upload .el-upload-dragger{
		height: 60px;
	}
	::v-deep .sku-image .vk-data-upload .el-upload--picture-card{
		width: 60px;
		height: 60px;
	}
	::v-deep .sku-image .vk-data-upload .el-upload{
		width: 60px;
		height: 60px;
		line-height: 60px;
	}
	::v-deep .sku-image .vk-data-upload .el-upload-list--picture-card .el-upload-list__item{
		width: 60px;
		height: 60px;
		line-height: 60px;
	}
	::v-deep .sku-image .vk-data-upload .el-upload-list--picture-card .el-upload-list__item-thumbnail{
		width: 60px;
		height: 60px;
		line-height: 60px;
	}
	::v-deep .sku-image .vk-data-upload .avatar{
		width: 60px;
		height: 60px;
	}
	::v-deep .sku-image .el-upload--picture-card i {
		font-size: 14px;
		color: #8c939d;
	}
	.hoverStyle:hover{ //批量修改之后按钮被hover之后对应样式
		transform: scale(1.1);
	}

</style>
